<template>
  <div class="medication-container">
    <div class="vertical-warning">温馨提示：这个提示很温馨</div>
    <h3><i class="fas fa-family"></i>家族病史管理</h3>


    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button
          v-if="!editMode"
          type="primary"
          @click="editMode = true"
          icon="el-icon-edit"
          class="action-btn"
      >编辑
      </el-button>
      <el-button
          v-if="!editMode"
          type="success"
          @click="addNewMedication"
          icon="el-icon-plus"
          class="action-btn"
      >新增
      </el-button>
      <el-button
          v-if="!editMode"
          type="warning"
          @click="toggleSort"
          icon="el-icon-sort"
          class="action-btn"
      >{{ sortButtonText }}
      </el-button>
      <template v-else>
        <el-button
            type="success"
            @click="saveChanges"
            icon="el-icon-check"
            class="confirm-btn"
        >保存
        </el-button>
        <el-button
            type="danger"
            @click="cancelEdit"
            icon="el-icon-close"
            class="cancel-btn"
        >取消
        </el-button>
      </template>
    </div>

    <div class="medication-list">
      <div
          class="medication-card"
          :class="{ 'sample-data': isSampleData }"
          v-for="(med, index) in medications"
          :key="med.recordId || index"
          @mousedown="createRipple"
      >
        <div class="medication-header">

          <span class="detail-label"><i class="far fa-clock"></i> ID:{{ med.recordId }}</span>
          <span class="detail-label"><i class="far fa-clock"></i>  病人姓名:</span>
          <div class="medication-name">

            <span v-if="!editMode"><i class="fas fa-capsules"></i> {{ med.patientName }}</span>
            <input v-else v-model="med.patientName" class="form-input" placeholder="病人姓名">
          </div>
          <div class="medication-status" v-if="!editMode">
            <i class="far fa-calendar-alt"></i> {{ med.recordDate }}
          </div>
        </div>

        <div class="medication-details">
          <div class="detail-row">
            <span class="detail-label"><i class="far fa-clock"></i> 记录时间:</span>
            <span v-if="!editMode">{{ med.recordDate }}</span>
            <input v-else type="date" v-model="med.recordDate" class="form-input">
          </div>

          <div class="detail-row">
            <span class="detail-label"><i class="fas fa-people-arrows"></i> 亲属关系:</span>
            <span v-if="!editMode">{{ med.relationship }}</span>
            <input v-else v-model="med.relationship" class="form-input" placeholder="亲属关系">
          </div>
          <div class="detail-row">
            <span class="detail-label"><i class="fas fa-question-circle"></i> 病名:</span>
            <span v-if="!editMode">{{ med.diseaseName }}</span>
            <input v-else v-model="med.diseaseName" class="form-input" placeholder="病名">
          </div>

          <div class="detail-row">
            <span class="detail-label"><i class="fas fa-question-circle"></i> 发病频次:</span>
            <span v-if="!editMode">{{ med.onsetFrequency }}</span>
            <input v-else v-model="med.onsetFrequency" class="form-input" placeholder="发病频次">
          </div>

          <div class="detail-row">
            <span class="detail-label"><i class="fas fa-check-circle"></i> 备注:</span>
            <span v-if="!editMode">{{ med.remarks }}</span>
            <input v-else v-model="med.remarks" class="form-input" placeholder="啦啦啦">
          </div>
        </div>

        <!-- 删除按钮放在每张卡片内 -->
        <div class="card-actions" v-if="editMode">
          <el-button
              type="danger"
              size="small"
              @click="deleteHandler(index)"
              icon="el-icon-delete"
          >删除
          </el-button>
        </div>
      </div>
    </div>


    <!-- 分页控件 -->
    <div class="pagination-controls" >
      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="totalRecords"
          :page-sizes="[1,2,4,8,10, 20, 30, 50]"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"


          @current-change="handlePageChange"
      />
    </div>

    <!-- 弹出对话框 -->
    <div class="popup-container" :class="{ 'show-popup': showAddDialog }">
      <div class="popup-backdrop" @click="showAddDialog = false"></div>
      <div class="popup-dialog" :class="{ 'scale-in': showAddDialog }">
        <div class="popup-header">
          <div class="popup-title">
            <i class="fas fa-plus-circle header-icon"></i>
            <h3>新增家族病史</h3>
          </div>
          <button class="close-button" @click="showAddDialog = false">
            <i class="el-icon-close"></i>
          </button>
        </div>

        <el-form :model="currentMedication" label-width="110px" class="popup-form">



          <el-form-item label="亲人姓名：" prop="medicationName">
            <el-input
                v-model="currentMedication.patientName"
                placeholder="请输入亲人姓名"
                class="custom-input"
                suffix-icon="el-icon-document"
            />
          </el-form-item>

          <el-form-item label="病名：" prop="usageAndDosage" >
            <el-input
                v-model="currentMedication.diseaseName"
                placeholder="病名"
                class="custom-input"
                suffix-icon="el-icon-timer"
            />
          </el-form-item>

          <el-form-item label="关系：" class="form-item-vertical">
            <el-input
                v-model="currentMedication.relationship"
                placeholder="请输入亲属关系"
                type="textarea"
                :rows="3"
                class="custom-textarea"
            />
          </el-form-item>

          <el-form-item label="发病情况：" class="form-item-vertical">
            <el-input
                v-model="currentMedication.onsetFrequency"
                placeholder="比如每天发一次颠"
                type="textarea"
                :rows="3"
                class="custom-textarea"
            />
          </el-form-item>

          <el-form-item label="备注：" class="form-item-vertical">
            <el-input
                v-model="currentMedication.remarks"
                placeholder="若有则填"
                type="textarea"
                :rows="3"
                class="custom-textarea"
            />
          </el-form-item>
        </el-form>

        <div class="popup-footer">
          <el-button
              class="custom-cancel-btn"
              @click="showAddDialog = false"
          >取消
          </el-button>
          <el-button
              type="primary"
              class="custom-confirm-btn"
              @click="saveNewMedication"
          >保存记录
          </el-button>
        </div>
      </div>
    </div>
    <div class="total-records-notice">
      <el-icon>
        <info-filled/>
      </el-icon>
      您共有{{ totalRecords }}个家族病史记录
    </div>
  </div>
</template>

<script setup>
import {computed, nextTick, onMounted, onUnmounted, reactive, ref} from 'vue';
import {createHealthRecord, deleteHealthRecord, getFamilyHistory, updateHealthRecord} from "@/api/profile.js";
import {ElButton, ElForm, ElFormItem, ElInput, ElMessage, ElMessageBox, ElPagination} from 'element-plus';
import {InfoFilled} from '@element-plus/icons-vue';
import { postLog } from "@/api/log.js"

const isSortedAscending = ref(true);
const sortButtonText = computed(() => isSortedAscending.value ? '按日期排序 ↑' : '按日期排序 ↓');

// 响应式状态
const editMode = ref(false);
const showAddDialog = ref(false);
const currentMedication = reactive({
  recordId: null,
  recordDate: new Date().toISOString().split('T')[0],
  recordType: '家族病史',
  patientName: '',
  diseaseName: '',
  relationship: '',
  onsetFrequency: '',
  remarks: ''
});
const medications = ref([]);
const originalMedications = ref([]);
const currentPage = ref(1);
const pageSize = ref(8);
const totalRecords = ref(0);
const isLoading = ref(false);
const isSampleData = ref(false);

// 用户状态监听
const userInfo = ref(null);
const handleUserLogout = () => {
  userInfo.value = null;
  medications.value = [];
};


// 生命周期钩子
onMounted(async () => {
  try {
    const storedUser = localStorage.getItem('currentUser');
    userInfo.value = storedUser ? JSON.parse(storedUser) : null;
    await loadMedications();
  } catch (error) {
    console.error('初始化失败:', error);
  }

  window.addEventListener('user-logout', handleUserLogout);
  window.addEventListener('storage', (e) => {
    if (e.key === 'currentUser' && !e.newValue) handleUserLogout();
  });
});

onUnmounted(() => {
  window.removeEventListener('user-logout', handleUserLogout);
});

// 业务逻辑方法
const loadMedications = async () => {
  isLoading.value = true;
  try {
    const res = await getFamilyHistory(userInfo.value?.id, {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    });
    isSortedAscending.value = !isSortedAscending.value;
    res.data.data.sort((a, b) => {
      return isSortedAscending.value
          ? a.recordDate.localeCompare(b.recordDate)
          : b.recordDate.localeCompare(a.recordDate);
    });
    if (res.data?.data) {
      const startIndex = (currentPage.value - 1) * pageSize.value;
      const endIndex = startIndex + pageSize.value;
      medications.value = res.data.data.slice(startIndex, endIndex);
      totalRecords.value = res.data.total || res.data.data.length;
      originalMedications.value = JSON.parse(JSON.stringify(res.data.data));
      isSampleData.value = false;
    }
  } catch (error) {
    isSampleData.value = true;
  } finally {
    isLoading.value = false;
  }
};
const toggleSort = () => {
  loadMedications();
};
const addNewMedication = () => {
  console.log('新增按钮点击事件触发');
  Object.assign(currentMedication, {
    recordId: null,
    recordDate: new Date().toISOString().split('T')[0],
    recordType: '家族病史',
    patientName: '',
    diseaseName: '',
    relationship: '',
    onsetFrequency: '',
    remarks: ''
  });

  // 触发对话框显示并添加动画类
  nextTick(() => {
    showAddDialog.value = true;
  });
};

const validateFamilyHistory = (history) => {
  if (!history.diseaseName?.trim()) {
    ElMessage.error('疾病名称不能为空');
    return false;
  }
  if (!history.relationship?.trim()) {
    ElMessage.error('亲属关系不能为空');
    return false;
  }
  return true;
};

const saveNewMedication = async () => {
  if (!validateFamilyHistory(currentMedication)) return;

  try {
    const submitData = {
      ...currentMedication,
      detail: `${currentMedication.patientName}|${currentMedication.diseaseName}|${currentMedication.relationship}|${currentMedication.onsetFrequency}|${currentMedication.remarks}|`
    };
    const response = await createHealthRecord(userInfo.value?.id, submitData);
    ElMessage.success('新增成功');
    showAddDialog.value = false;
    await loadMedications();

    // 修改操作日志记录
    if (userInfo.value) {
      for (const med of medications.value) {
        await postLog({
          id: userInfo.value.id,
          role: userInfo.value.role,
          username: userInfo.value.username,
          ip: userInfo.value.ip || '192.66.55.4', // 若 IP 不存在则设为空字符串
          loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
          recordType: '家族病史',
          action: '修改',
          recordId: response.recordId,
          logTime: new Date().toISOString() // 添加 logTime 属性
        });
      }
    }
  } catch (error) {
    ElMessage.error('新增失败：' + error.message);
  }
};

const saveChanges = async () => {
  if (medications.value.some(med => !validateFamilyHistory(med))) return;

  try {
    const promises = medications.value.map(async (med) => {
      const submitData = {
        recordId: med.recordId,
        recordDate: med.recordDate,
        recordType: '家族病史',
        detail: `${med.patientName}|${med.diseaseName}|${med.relationship}|${med.onsetFrequency}|${med.remarks}`
      };
      return med.recordId
          ? await updateHealthRecord(submitData)
          : await createHealthRecord(userInfo.value?.id, submitData);
    });

    await Promise.all(promises);
    ElMessage.success('保存成功');
    editMode.value = false;
    await loadMedications();

    // 修改操作日志记录
    if (userInfo.value) {
      for (const med of medications.value) {
        await postLog({
          id: userInfo.value.id,
          role: userInfo.value.role,
          username: userInfo.value.username,
          ip: userInfo.value.ip || '192.66.55.4', // 若 IP 不存在则设为空字符串
          loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
          recordType: '家族病史',
          action: '修改',
          recordId: med.recordId,
          logTime: new Date().toISOString() // 添加 logTime 属性
        });
      }
    }
  } catch (error) {
    ElMessage.error('保存失败：' + error.message);
  }
};

const cancelEdit = () => {
  editMode.value = false;
  medications.value = JSON.parse(JSON.stringify(originalMedications.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)));
};

const deleteHandler = async (index) => {
  try {
    await ElMessageBox.confirm('确定删除该条家族病史吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const recordId = medications.value[index].recordId;
    if (recordId) {
      await deleteHealthRecord(recordId);
    }
    medications.value.splice(index, 1);
    ElMessage.success('删除成功');

    if (medications.value.length === 0 && currentPage.value > 1) {
      currentPage.value--;
      await loadMedications();
    }
    // 删除操作日志记录
    if (userInfo.value) {
      await postLog({
        id: userInfo.value.id,
        role: userInfo.value.role,
        username: userInfo.value.username,
        ip: userInfo.value.ip || '192.66.55.4', // 若 IP 不存在则设为空字符串
        loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
        recordType: '家族病史',
        action: '删除',
        recordId: recordId,
        logTime: new Date().toISOString() // 添加 logTime 属性
      });
    }
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('删除失败：' + error.message);
  }
};

const handlePageChange = (page) => {
  isSortedAscending.value = !isSortedAscending.value;

  currentPage.value = page;
  loadMedications();
};
const handleSizeChange = (val) =>{
  currentPage.value=1;
  pageSize.value = val;
  loadMedications();
}
</script>

<style scoped>
@import "@/assets/css/new.css";

</style>